<?php
/*********************************************
 *  CPG Dragonfly™ CMS
 *********************************************
	Copyright © since 2010 by CPG-Nuke Dev Team
	http://dragonflycms.org

	Dragonfly is released under the terms and conditions
	of the GNU GPL version 2 or any later version

	$Source$
	$Revision$
	$Author$
	$Date$
**********************************************/

abstract class Poodle_URI
{

	public static function resolve($uri='', $query=null)
	{
		if ($uri && '/' === $uri[0]) {
			$base = null;
			$s = substr($uri,0,7);
			if ('/admin/'===$s) {
				$uri = substr($uri,6);
				$base = Poodle::$URI_ADMIN;
			} else
			if ('/media/'===$s) {
				$uri = substr($uri,6);
				$base = Poodle::$URI_MEDIA;
			} else
			if (is_file(substr($uri,1))) {
				return Poodle::$URI_BASE.$uri;
			}
			return self::index($uri, $query, $base);
		}
		return $uri;
	}

	public static function index($str)
	{
		return URL::index($str);
	}

	/**
	 * Workaround, because parse_str() converts dots and spaces in variable
	 * names to underscores, as noted on http://php.net/parse_str
	 * and on http://php.net/manual/en/language.variables.external.php
	 */
	public static function parse_query($str)
	{
		if (is_array($str)) return $str;
		$data = array();
		if (is_string($str))
		{
			$parts = explode('&', $str);
			foreach ($parts as $part)
			{
				$pair = explode('=', $part, 2);
				if (2 == count($pair)) {
					$data[urldecode($pair[0])] = urldecode($pair[1]);
				} else {
					$data[urldecode($part)] = '';
				}
			}
		}
		return $data;
	}

	public static function shrink($uri, $len=35)
	{
		$uri = preg_replace('#^[a-z]+?://#i', '', $uri);
		return (strlen($uri) > $len) ? substr($uri,0,round($len*2/3)).'...'.substr($uri,3-round($len/3)) : $uri;
	}

	public static function encode($uri)
	{
		return preg_replace('#([\x20\x22\x3C\x3E])#e', '\'%\'.bin2hex(stripslashes(\'$1\'))', $uri);
	}

	public static function appendArgs($uri, array $args)
	{
		$uri_q = parse_url($uri, PHP_URL_QUERY);
		if ($uri_q) { $args = array_merge(self::parse_query($uri_q), $args); }
		$uri = preg_replace('#\?.*#','',$uri);
		if ($args) { $uri .= '?'.http_build_query($args, '', '&'); }
		return $uri;
	}

	public static function isHTTPS($url) { return 0 === strpos($url,'https://'); }

}
